"""媒体库列表页面处理器模块"""

from typing import Optional
from aiohttp import web
from dashboard.data_manager import DataManager

router = web.RouteTableDef()

# 数据管理器实例，将在main.py中注入
data_manager: Optional[DataManager] = None


def set_data_manager(manager: DataManager):
    """设置数据管理器实例"""
    global data_manager
    data_manager = manager


@router.get("/")
def index_handler(request: web.Request):
    """媒体库列表页面"""
    html_content = '''
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Emby媒体库管理</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                color: #333;
            }
            .navbar {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 1rem 2rem;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .nav-container {
                max-width: 1200px;
                margin: 0 auto;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            
            /* 桌面端样式 */
            @media (min-width: 768px) {
                .nav-container {
                    flex-direction: row;
                    justify-content: space-between;
                }
            }
            .nav-title {
                color: white;
                font-size: 1.5rem;
                font-weight: bold;
                font-family: 'BM HANNA Pro OTF', sans-serif;
            }
            .nav-links {
                display: flex;
                gap: 2rem;
            }
            .nav-link {
                color: white;
                text-decoration: none;
                padding: 0.5rem 1rem;
                border-radius: 5px;
                transition: background-color 0.3s;
            }
            .nav-link:hover, .nav-link.active {
                background-color: rgba(255,255,255,0.2);
            }
            .container {
                max-width: 1200px;
                margin: 2rem auto;
                padding: 0 2rem;
            }
            .page-title {
                text-align: center;
                margin-bottom: 2rem;
                color: #333;
            }
            .server-info {
                background: #e3f2fd;
                padding: 1rem;
                border-radius: 8px;
                margin-bottom: 2rem;
                text-align: center;
            }
            .libraries-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
                gap: 1.5rem;
                margin-top: 1rem;
            }
            .library-card {
                background: transparent;
                border: 1px solid rgba(255, 255, 255, 0.3);
                border-radius: 15px;
                padding: 0;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                transition: transform 0.3s, box-shadow 0.3s;
                position: relative;
                overflow: hidden;
                aspect-ratio: 16 / 9;
                min-height: 200px;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
            }
            .library-card.with-cover::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-image: var(--cover-url);
                background-size: cover;
                background-position: center;
                background-repeat: no-repeat;
                z-index: 1;
            }
            .library-card-content {
                position: relative;
                z-index: 2;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
            }
            .library-card-content .library-name {
                font-size: 1.5rem;
                font-weight: bold;
                color: var(--text-color, white);
                text-shadow: var(--text-shadow, 2px 2px 4px rgba(0, 0, 0, 0.7));
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 1rem;
                border-radius: 8px;
                background: transparent;
            }
            .library-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            }
            .library-type {
                display: inline-block;
                padding: 0.15rem 0.4rem;
                border-radius: 10px;
                font-size: 0.6rem;
                font-weight: bold;
                text-transform: uppercase;
                letter-spacing: 0.3px;
                margin-left: 0.5rem;
                box-shadow: 0 1px 4px rgba(0,0,0,0.3);
                border: 1px solid rgba(255,255,255,0.3);
                backdrop-filter: blur(10px);
            }
            
            .library-type.movies {
                background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.music {
                background: linear-gradient(135deg, #48cae4 0%, #0096c7 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.homevideos {
                background: linear-gradient(135deg, #9b5de5 0%, #7209b7 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.playlists {
                background: linear-gradient(135deg, #f9c74f 0%, #f8961e 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.boxsets {
                background: linear-gradient(135deg, #90be6d 0%, #43aa8b 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.default {
                background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }

            /* 启用按钮样式优化 */
            .toggle-btn {
                position: relative;
                padding: 0.4rem 0.75rem;
                border: none;
                border-radius: 15px;
                font-size: 0.7rem;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
                overflow: hidden;
                min-width: 60px;
            }

            .toggle-btn::before {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
                transition: left 0.6s;
            }

            .toggle-btn:hover::before {
                left: 100%;
            }

            .toggle-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            }

            .toggle-btn:active {
                transform: translateY(0);
                box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
            }

            .toggle-btn.enabled {
                background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
                box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
            }

            .toggle-btn.enabled:hover {
                box-shadow: 0 8px 25px rgba(76, 175, 80, 0.4);
            }

            .toggle-btn.disabled {
                background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
                box-shadow: 0 4px 15px rgba(244, 67, 54, 0.3);
            }

            .toggle-btn.disabled:hover {
                box-shadow: 0 8px 25px rgba(244, 67, 54, 0.4);
            }

            .toggle-btn:disabled {
                opacity: 0.6;
                cursor: not-allowed;
                transform: none;
                box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            }

            .toggle-btn:disabled::before {
                display: none;
            }

            .status-indicator {
                display: inline-block;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                margin-right: 6px;
                animation: pulse 2s infinite;
            }

            .status-indicator.enabled {
                background: #4CAF50;
                box-shadow: 0 0 5px #4CAF50;
            }

            .status-indicator.disabled {
                background: #f44336;
                box-shadow: 0 0 5px #f44336;
            }

            @keyframes pulse {
                0% { transform: scale(1); opacity: 1; }
                50% { transform: scale(1.2); opacity: 0.7; }
                100% { transform: scale(1); opacity: 1; }
            }

            .card-status {
                position: absolute;
                top: 10px;
                right: 10px;
                display: flex;
                align-items: center;
                background: rgba(0,0,0,0.7);
                padding: 4px 8px;
                border-radius: 12px;
                color: white;
                font-size: 0.7rem;
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255,255,255,0.2);
            }
            .btn {
                padding: 0.5rem 1rem;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                font-size: 0.9rem;
                transition: all 0.3s;
            }
            .btn-primary {
                background: #667eea;
                color: white;
            }
            .btn-primary:hover {
                background: #5a6fd8;
            }
            .btn-primary:disabled {
                background: #ccc;
                cursor: not-allowed;
            }
            .loading {
                text-align: center;
                padding: 3rem;
                color: #666;
            }
            .error {
                background: #ffebee;
                color: #c62828;
                padding: 1rem;
                border-radius: 5px;
                text-align: center;
                margin: 1rem 0;
            }
            .success {
                background: #e8f5e8;
                color: #2e7d32;
                padding: 1rem;
                border-radius: 5px;
                text-align: center;
                margin: 1rem 0;
            }
            .hidden {
                display: none;
            }
        </style>
    </head>
    <body>
        <nav class="navbar">
            <div class="nav-container">
                <div class="nav-title">Mocaca</div>
                <div class="nav-links">
                        <a href="/" class="nav-link active">媒体库</a>
                        <a href="/phone-playlists" class="nav-link">播放列表</a>
                        <a href="/douyin-sources" class="nav-link">数据源</a>
                        <a href="/settings" class="nav-link">设置</a>
                    </div>
            </div>
        </nav>

        <div class="container">
            <!-- 主页 - 媒体库列表 -->
            <div id="home-page">
                <h1 class="page-title">Emby媒体库展示</h1>
                
                <div class="server-info">
                    <strong>服务器信息:</strong> 192.168.50.46:8096 | Emby版本: 4.8.11.0
                </div>

                <div id="libraries-container">
                    <div class="loading">正在加载媒体库列表...</div>
                </div>
            </div>
        </div>

        <script>
            let libraries = [];

            // 加载媒体库列表（主页）
            async function loadLibraries() {
                try {
                    const response = await fetch('/api/libraries');
                    const data = await response.json();
                    
                    const container = document.getElementById('libraries-container');
                    
                    if (data.success) {
                        libraries = data.libraries;
                        if (libraries.length === 0) {
                            container.innerHTML = '<div class="error">未找到媒体库</div>';
                            return;
                        }
                        
                        const librariesHtml = libraries.map(lib => {
                            const coverStyle = lib.cover_url ? `style="--cover-url: url('${lib.cover_url}')"` : '';
                            const coverClass = lib.cover_url ? 'library-card with-cover' : 'library-card';
                            return `
                            <div class="${coverClass}" ${coverStyle} data-lib-id="${lib.id}">
                                <div class="library-card-content">
                                    <div class="library-name">
                                        ${lib.name}
                                        <span class="library-type ${lib.type}">${lib.type}</span>
                                    </div>
                                </div>
                            </div>
                        `}).join('');
                        
                        container.innerHTML = `
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                                <h2>媒体库列表 (${libraries.length}个)</h2>
                                <button id="refresh-libraries-btn" class="btn btn-primary">
                                    刷新媒体库
                                </button>
                            </div>
                            <div class="libraries-grid">${librariesHtml}</div>
                        `;
                        
                        // 添加刷新按钮点击事件
                        document.getElementById('refresh-libraries-btn').addEventListener('click', async function() {
                            const btn = this;
                            btn.disabled = true;
                            btn.textContent = '刷新中...';
                            
                            try {
                                const response = await fetch('/api/libraries/refresh');
                                const data = await response.json();
                                
                                if (data.success) {
                                    await loadLibraries();
                                    showMessage('媒体库数据已成功刷新', 'success');
                                } else {
                                    showMessage(`刷新失败: ${data.error}`, 'error');
                                }
                            } catch (error) {
                                showMessage(`网络错误: ${error.message}`, 'error');
                            } finally {
                                btn.disabled = false;
                                btn.textContent = '刷新媒体库';
                            }
                        });
                    } else {
                        container.innerHTML = `
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                                <h2>媒体库列表 (0个)</h2>
                                <button id="refresh-libraries-btn" class="btn btn-primary">
                                    刷新媒体库
                                </button>
                            </div>
                            <div class="error">加载失败: ${data.error}</div>
                        `;
                        
                        // 添加刷新按钮点击事件
                        document.getElementById('refresh-libraries-btn').addEventListener('click', async function() {
                            const btn = this;
                            btn.disabled = true;
                            btn.textContent = '刷新中...';
                            
                            try {
                                const response = await fetch('/api/libraries/refresh');
                                const data = await response.json();
                                
                                if (data.success) {
                                    await loadLibraries();
                                    showMessage('媒体库数据已成功刷新', 'success');
                                } else {
                                    showMessage(`刷新失败: ${data.error}`, 'error');
                                }
                            } catch (error) {
                                showMessage(`网络错误: ${error.message}`, 'error');
                            } finally {
                                btn.disabled = false;
                                btn.textContent = '刷新媒体库';
                            }
                        });
                    }
                } catch (error) {
                    document.getElementById('libraries-container').innerHTML = 
                        `<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                            <h2>媒体库列表 (0个)</h2>
                            <button id="refresh-libraries-btn" class="btn btn-primary">
                                刷新媒体库
                            </button>
                        </div>
                        <div class="error">网络错误: ${error.message}</div>`;
                    
                    // 添加刷新按钮点击事件
                    document.getElementById('refresh-libraries-btn').addEventListener('click', async function() {
                        const btn = this;
                        btn.disabled = true;
                        btn.textContent = '刷新中...';
                        
                        try {
                            const response = await fetch('/api/libraries/refresh');
                            const data = await response.json();
                            
                            if (data.success) {
                                await loadLibraries();
                                showMessage('媒体库数据已成功刷新', 'success');
                            } else {
                                showMessage(`刷新失败: ${data.error}`, 'error');
                            }
                        } catch (error) {
                            showMessage(`网络错误: ${error.message}`, 'error');
                        } finally {
                            btn.disabled = false;
                            btn.textContent = '刷新媒体库';
                        }
                    });
                }
            }

            // 自适应文字颜色函数
            function getContrastColor(img) {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
                
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                const data = imageData.data;
                
                let r = 0, g = 0, b = 0;
                let count = 0;
                
                // 采样图片中心区域
                const startX = Math.floor(canvas.width * 0.25);
                const endX = Math.floor(canvas.width * 0.75);
                const startY = Math.floor(canvas.height * 0.25);
                const endY = Math.floor(canvas.height * 0.75);
                
                for (let y = startY; y < endY; y += 5) {
                    for (let x = startX; x < endX; x += 5) {
                        const index = (y * canvas.width + x) * 4;
                        r += data[index];
                        g += data[index + 1];
                        b += data[index + 2];
                        count++;
                    }
                }
                
                if (count === 0) return { color: 'white', shadow: '2px 2px 4px rgba(0, 0, 0, 0.7)' };
                
                r = Math.floor(r / count);
                g = Math.floor(g / count);
                b = Math.floor(b / count);
                
                // 计算亮度 (YIQ公式)
                const brightness = (r * 299 + g * 587 + b * 114) / 1000;
                
                // 根据亮度选择文字颜色
                if (brightness > 128) {
                    return { color: 'black', shadow: '2px 2px 4px rgba(255, 255, 255, 0.7)' };
                } else {
                    return { color: 'white', shadow: '2px 2px 4px rgba(0, 0, 0, 0.7)' };
                }
            }
            
            // 为每个卡片设置自适应文字颜色
            function setAdaptiveTextColors() {
                document.querySelectorAll('.library-card.with-cover').forEach(card => {
                    const img = new Image();
                    img.crossOrigin = 'anonymous';
                    // 正确提取URL，移除url()包装
                    let url = card.style.getPropertyValue('--cover-url');
                    if (url.startsWith('url(') && url.endsWith(')')) {
                        url = url.slice(4, -1).trim();
                        // 移除可能的引号
                        if ((url.startsWith('"') && url.endsWith('"')) || (url.startsWith("'") && url.endsWith("'"))) {
                            url = url.slice(1, -1);
                        }
                    }
                    img.src = url;
                    
                    img.onload = function() {
                        const contrast = getContrastColor(img);
                        card.style.setProperty('--text-color', contrast.color);
                        card.style.setProperty('--text-shadow', contrast.shadow);
                    };
                    
                    img.onerror = function() {
                        // 如果图片加载失败，使用默认白色文字
                        card.style.setProperty('--text-color', 'white');
                        card.style.setProperty('--text-shadow', '2px 2px 4px rgba(0, 0, 0, 0.7)');
                    };
                });
            }
            
            // 显示消息提示
            function showMessage(message, type = 'info') {
                // 移除之前的消息
                const existingMessage = document.getElementById('message-notification');
                if (existingMessage) {
                    existingMessage.remove();
                }
                
                // 创建新消息元素
                const messageDiv = document.createElement('div');
                messageDiv.id = 'message-notification';
                messageDiv.className = type;
                messageDiv.textContent = message;
                
                // 添加到页面顶部
                const container = document.querySelector('.container');
                container.insertBefore(messageDiv, container.firstChild);
                
                // 3秒后自动移除
                setTimeout(() => {
                    messageDiv.style.transition = 'opacity 0.5s ease-out';
                    messageDiv.style.opacity = '0';
                    setTimeout(() => {
                        messageDiv.remove();
                    }, 500);
                }, 3000);
            }
    
            // 页面加载完成后初始化
            document.addEventListener('DOMContentLoaded', function() {
                loadLibraries().then(() => {
                    // 延迟执行文字颜色自适应，确保图片已加载
                    setTimeout(setAdaptiveTextColors, 500);
                });
            });
        </script>
    </body>
    </html>
    '''
    
    return web.Response(text=html_content, content_type='text/html')


# API处理函数已在main.py中实现